package com.hzjq.core.impl

import com.hzjq.core.ErrorCode
import com.hzjq.core.bean.ErrorReadCapEntity
import com.hzjq.core.bean.ErrorResult
import com.hzjq.core.callback.Callback
import com.hzjq.core.callback.OnAuthCallback
import com.hzjq.core.callback.ProgressCallback
import com.hzjq.core.loader.OnAuthCapLoader
import com.hzjq.core.work.Works
import com.hzjq.core.worker.*
import io.reactivex.functions.Consumer

class AuthCapImpl : OnAuthCapLoader {

    private var works: Works? = null

    override fun onAuthCap(maxDelay: Long, callback: OnAuthCallback) {
        CheckerImpl().setCallback(Consumer {
            if (it) {
                cancel()
                val authErrorCall = object : ProgressCallback<ErrorReadCapEntity> {
                    override fun onResult(t: ErrorReadCapEntity) {
                        callback.onAuthErrorResult(t)
                    }

                    override fun onRetryCountChanged(retryCount: Int, action: String) {
                        callback.onRetryCountChanged(retryCount, action)
                    }

                    override fun onError(errorCode: ErrorResult) {
                        callback.onError(errorCode)
                    }

                    override fun onProgressChanged(progress: Int, total: Int, action: String) {
                        callback.onProgressChanged(progress / 2, 100, action)
                    }

                }

                works = Works.Builder.newBuilder()
                    .addWork(InnerAuthModeWork(callback))
                    .addWork(AuthQueryWork(callback, authErrorCall))
                    .addWork(InnerCheckTimeWork(callback))
                    .addWork(CheckTimeQueryWork(maxDelay, callback, authErrorCall))
                    .build()
                    .queue()
            } else {
                callback.onError(ErrorCode.getErrorResult(103))
            }
        })
    }

    override fun exitAuth(callback: Callback<Boolean>) {
        CheckerImpl().setCallback(Consumer {
            if (it) {
                BackWork(callback).doWork()
                works?.onDestroy()
            } else {
                callback.onError(ErrorCode.getErrorResult(103))
            }
        }).start()
    }

    override fun cancel() {
        works?.onDestroy()
    }
}